package com.homework.module6part3.service.impl;

import com.homework.module6part3.service.StockService;
import com.homework.util.ResultMsg;
import com.homework.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

@Service
public class StockServiceImpl implements StockService {
    protected static Jedis jedis = new Jedis();

    private static final String SECKILL_STOCK = "seckill_stock_";
    
    //
    public ResultMsg checkStock(int id) {
        String key = getStockKey(id);
        String val = jedis.get(key);
        int stock  = 0;
        if(val == null) {
            return ResultUtil.error(101, "库存尚未初始化， 请检查库存是否正确");
        } else {
            stock = Integer.parseInt(val);
        }
        if(stock <= 0 ) {
            return ResultUtil.error(100, "没有库存");
        }

        return ResultUtil.success(stock);
    }

    /**
     * 扣减库存
     * @return
     */
    public Long dedStock(int goodsId, int num) {
        String key = getStockKey(goodsId);
        Long leftStock  = jedis.incrBy(key, num);

        return leftStock;
    }

    protected String getStockKey(int goodsId) {
        String key = SECKILL_STOCK + Integer.toString(goodsId);
        return key;
    }
}
